package com.lixh.sdk.base.promision.contract

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.activity.result.contract.ActivityResultContract
import androidx.annotation.RequiresApi

@RequiresApi(Build.VERSION_CODES.O)
class RequestInstallAppContract : ActivityResultContract<Unit, Boolean>() {
    var context: Context? = null

    override fun createIntent(context: Context, input: Unit): Intent {
        this.context = context
        return Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).apply {
            data = Uri.fromParts("package", context.packageName, null)
        }
    }

    override fun getSynchronousResult(
        context: Context,
        input: Unit
    ): SynchronousResult<Boolean>? {
        if (context.packageManager.canRequestPackageInstalls()) {
            return SynchronousResult(true)
        }
        return null
    }

    override fun parseResult(resultCode: Int, intent: Intent?): Boolean =
        context?.packageManager?.canRequestPackageInstalls() ?: false
}